package com.filldream.fastboot.core.manager;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.filldream.fastboot.base.entity.Role;
import com.filldream.fastboot.base.entity.SysDept;
import com.filldream.fastboot.base.mapper.RoleMapper;
import com.filldream.fastboot.common.entity.ErrorCode;
import com.filldream.fastboot.common.util.Assert;
import com.filldream.fastboot.core.LoginHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author RickSun && iFillDream
 * @version 1.0
 * @data 2020-08-11 14:43
 * @description 角色-缓存管理器
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleManager {

    @Resource
    private RoleMapper roleMapper;


    public Role getById( Long roleId ){
        Role role = roleMapper.selectById(roleId);
        return role;
    }

    public Integer modify( Role role ){
        if( role.getId().equals(1L) ){
            role.setDataScope(1);
        }

        Assert.isBoolean( role.getId().equals(LoginHolder.getPcRoleId()) && !role.getId().equals(1L), ErrorCode.BASE_ERR.reMsg("您无权修改您当前的角色的信息和权限") );

        return roleMapper.updateById(role);
    }

    public Integer del( Long roleId ){
        return roleMapper.deleteById(roleId);
    }


    public List<Long> getChildRoleIdList(boolean hasMe, Role thisRole) {

        List<Role> roleList = roleMapper.selectList(new QueryWrapper<Role>().ge("id", thisRole.getId()));

        List<Long> result = new ArrayList<>();

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setChildrenKey("children");
        treeNodeConfig.setIdKey("id");
        List<Tree<String>> treeNodes = TreeUtil.build(roleList, thisRole.getPId()+"", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getPId()+"");
                    result.add(treeNode.getId());
                });

        if( !hasMe ){
            result.remove(thisRole.getId());
        }

        return result;
    }
}
